<?php
namespace app\api\service;
use think\Controller;
use think\Db;
use think\Exception;
use think\Loader;
use think\Session;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/26 0026
 * Time: 15:40
 */

class Order extends Controller {

    /**
     * 创建需求订单
     * @param $param
     * @return mixed
     */
    public static function create_demand_order($param) {
        try {
            $member = model('member')->get(['id' => $param['member_id']]);
            $order_data = [
                'member_id' => $param['member_id'],
                //'member_id' => 0,
                'order_sn' => 'JX' . date('YmdHis') . rand(1000, 9999),
                'drink_time' => strtotime($param['drink_time']),
                'address' => $param['address'],
                'consignee' => $param['consignee'],
                'mobile' => $param['mobile'],
                'lat' => $param['lat'],
                'lng' => $param['lng'],
                'msg' => $param['msg'],
                'consignment_type' => $param['consignment_type']
            ];

            $validate = Loader::validate('Order');
            if(!$validate->scene('demand')->check($order_data)){
                throw new \Exception($validate->getError());
            }

            $model = model('order');
            $model->save($order_data);

            // 订单创建成功给附近商店推送消息
            $where['sc.category_id'] = $param['category_id'];
            // 根据用户经纬度 获取附近活动
            $coord = getAround($param['lat'], $param['lng'], 10000);
            $where['s.lat'] = ['between', [$coord[0], $coord[1]]];
            $where['s.lng'] = ['between', [$coord[2], $coord[3]]];
            //return api_return('200',$coord);
            $shop_list = model('shop_category')->alias('sc')->field('m.openid, sc.shop_id, s.member_id')
                ->join('jx_shop s', 's.id = sc.shop_id')
                ->join('jx_member m', 'm.id = s.member_id')
                ->where($where)
                ->select();

            $accountList = [];
            foreach ($shop_list as $v) {
                $url = request()->domain() . url('index/shop/vie_for_order_info', ['shop_id' => $v->shop_id, 'id' => $model->id]);
                $param = [
                    'touser' => $v['openid'],
                    'template_id' => 'uEoTbd3NTsr84nmKXDIuqHgkad-TyeghRRcvhHNwB0M',
                    'url' => $url,
                    'data' => [
                        'first' => [ 'value' => '发现一条新的订单。', 'color' => '#173177'],
                        'tradeDateTime' => [ 'value' => date('Y-m-d H:i:s'), 'color' => '#173177'],
                        'orderType' => [ 'value' => '我要喝酒', 'color' => '#173177'],
                        'customerInfo' => [ 'value' => $member->memberRoleInfo->nickname . ' ' . $member->username, 'color' => '#173177'],
                        'orderItemName' => [ 'value' => '备注信息', 'color' => '#173177'],
                        'orderItemData' => [ 'value' => $order_data['msg'], 'color' => '#173177'],
                        'remark' => [ 'value' => '请尽快接单为客户提供服务', 'color' => '#173177'],
                    ]
                ];
                send_msg($param);

                $accountList[] = (string)$v->member_id;

                Xinge::AndroidPushSingleAccount((string)$v->member_id, '新订单通知', '发现一条新的订单。', ['id' => $model->id, 'shop_id' => $v->shop_id], 'com.jiuxing.wine.my_store.activity.RequireWaitRobDetailActivity');
            }

            /**
             *  APP推送
             */
            if ($accountList) {
//                Xinge::AndroidPushAccountList($accountList, '新订单通知', '发现一条新的订单。', ['id' => $model->id], 'com.jiuxing.wine.my_store.activity.RequireWaitRobDetailActivity');
                Xinge::IosPushAccountList(['428'], '发现一条新的订单。',  ['id' => $model->id]);
            }

            return api_return(200, ['id' => $model->id]);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 确认订单
     * @param $param
     * @return array
     */
    public static function affirm_order($param) {
        try {

            $data = [];

            // + ------- 收货地址信息  -------- + //
            $address_id = isset($param['address_id']) ? $param['address_id'] : 0;
            if ($address_id > 0) {
                $address = Address::get_address_info(['id' => $address_id, 'member_id' => $param['member_id']]);
            } else {
                $address = Address::get_default_address_info(['member_id' => $param['member_id']]);
            }
            $data['address'] = $address['data'];

            $shop_product = model('cart')->where('id', 'in', $param['cart_id'])->select();
            $total_price = $total_num = 0;
            foreach ($shop_product as $v) {
                $total_num += $v->num;
                $total_price += $v->product->price * $v->num;

                $data['product'][$v->shop_id]['name'] = $v->shop->name;
                $data['product'][$v->shop_id]['logo'] = get_img_url($v->shop->logo);
                $data['product'][$v->shop_id]['level'] = $v->shop->commentLevel() > 0 ? $v->shop->commentLevel() : 5;
                $data['product'][$v->shop_id]['list'][] = [
                    'id' => $v->id,
                    'product_id' => $v->product_id,
                    'product_name' => $v->product->name,
                    'thumb' => get_img_url($v->product->thumb),
                    'price' => $v->product->price,
                    'num' => $v->num,
                ];
            }

            foreach ($data['product'] as $k => $v) {
                $v['shop_id'] = $k;
                $product[] = $v;
            }
            $data['product'] = $product;
            $data['cart_ids'] = is_array($param['cart_id']) ? implode(',', $param['cart_id']) : $param['cart_id'];
            $data['price'] = $total_price;
            $data['total_price'] = number_format($total_price, 2);
            $data['total_num'] = $total_num;

            return api_return(200, $data);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 创建订单
     * @param $param
     * @return array
     */
    public static function create_order($param) {
        try {
            $affirm_order_data = self::affirm_order($param);  // 从确认订单接口获取相关数据

            /************************************************
             * 订单创建逻辑
             * 1.检查购物车商品是否来自同一家店
             * 2.如果是，则只用创建一个订单；如果来自多家店，则创建一个主订单用于支付，另外按店铺创建子订单
             * 3.优惠券，琼露（积分）暂未处理  2017-09-06 15:41
            ***/
            if (count($affirm_order_data['data']['product']) > 1) {
                // 创建主订单
                $main_order_data = [
                    'member_id' => $param['member_id'],
                    'order_sn' => 'JX' . date('YmdHis') . rand(1000, 9999),
                    'price' => $affirm_order_data['data']['price'],
                    'is_main_order' => 2
                ];
                model('order')->save($main_order_data);
                $order_id = model('order')->id;
            }

            // 循环产品列表　按店铺创建订单
            foreach ($affirm_order_data['data']['product'] as $k => $v) {
                $price = 0;
                $order_sn = 'JX' . date('YmdHis') . rand(1000, 9999);
                foreach ($v['list'] as $p) {
                    // 组装订单产品
                    $order_product_data[] = [
                        'order_sn' => $order_sn,
                        'product_id' => $p['product_id'],
                        'name' => $p['product_name'],
                        'image' => $p['thumb'],
                        'price' => $p['price'],
                        'num' => $p['num']
                    ];
                    $price += $p['num'] * $p['price'];
                }

                // 组装订单数据
                $order_data[] = [
                    'member_id' => $param['member_id'],
                    'order_sn' => $order_sn,
                    'price' => $price,
                    'address' => $affirm_order_data['data']['address']['address'],
                    'consignee' => $affirm_order_data['data']['address']['linkman'],
                    'mobile' => $affirm_order_data['data']['address']['mobile'],
                    'msg' => isset($param['shop_msg']['shop_id_' . $v['shop_id']]) ? $param['shop_msg']['shop_id_' . $v['shop_id']] : '',
                    'consignment_type' => isset($param['consignment_type']['shop_id_' . $v['shop_id']]) ? $param['consignment_type']['shop_id_' . $v['shop_id']] : '送货上门',
                    'type' => 2,
                    'shop_id' => $v['shop_id'],
                    'main_order_sn' => isset($main_order_data) ? $main_order_data['order_sn'] : ''
                ];
            }
            if (isset($order_data) && !empty($order_data) && isset($order_product_data) && !empty($order_product_data)) {
                // 订单入库
                if (isset($main_order_data)) {  // 多店铺订单，批量入库
                    model('order')->saveAll($order_data);
                } else {
                    model('order')->save($order_data[0]); // 单店铺订单，入库一条记录，并获取ＩＤ
                    $order_id = model('order')->id;
                }

                // 订单产品入库
                model('order_product')->saveAll($order_product_data);
            } else {
                throw new \Exception('订单创建失败');
            }

            // 订单创建成功 删除购物车
            model('cart')->where('id', 'in', $param['cart_id'])->delete();

            return api_return(200, ['order_id' => $order_id]);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 获取用户订单列表
     * @param $param
     * @return array
     */
    public static function get_member_order_list($param) {
        try {
            $where = [
                'member_id' => $param['member_id'],
                'is_main_order' => 1
            ];

            $list = model('order')->where($where)->order('id desc')->paginate();
            $data = [];
            if ($list) {
                $data['list'] = [];
                foreach ($list as $k => $v) {
                    $product = []; $product_num = 0;
                    if ($v->type == 2 || ($v->type == 1 && $v->status == 3)) {
                        $order_product = model('order_product')->where('order_sn', $v->order_sn)->select();
                        foreach ($order_product as $p) {
                            $product_num += $p->num;
                            $product[] = [
                                'id' => $p->product_id,
                                'name' => $p->name,
                                'image' => $p->image,
                                'price' => number_format($p->price, 2),
                                'num' => $p->num,
                            ];
                        }
                    }

                    $data['list'][] = [
                        'id' => $v->id,
                        'type' => $v->type,
                        'create_time' => $v->create_time,
                        'status' => $v->status,
                        'status_text' => get_order_status($v->status, $v->type),
                        'comment_status' => $v->comment_status,
                        'after_status' => $v->after_status,
                        'price' => number_format($v->price, 2),
                        'msg' => $v->msg,
                        'express_sn' => $v->express_sn,
                        'shop_id' => $v->shop_id,
                        'shop_logo' => $v->shop_id ? get_img_url($v->shop->logo) : '',
                        'shop_name' => $v->shop_id ? $v->shop->name : '',
                        'shop_level' => $v->shop_id ? ($v->shop->commentLevel() > 0 ? $v->shop->commentLevel() : 5) : 5,
                        'products' => $product,
                        'products_num' => $product_num
                    ];
                }
                $list = $list->toArray();
                $is_more = $list['total'] - ($list['current_page'] * $list['per_page']);
                $data['is_more'] = $is_more;
            }

            return api_return(200, $data);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 获取订单详情
     * @param $param
     * @return array
     */
    public static function get_order_info($param) {
        try {
            $order = model('order')->get(['id' => $param['id'], 'member_id' => $param['member_id']]);
            $products = model('order_product')->where('order_sn', $order->order_sn)->select();
            $product = [];
            $product_num = 0;
            foreach ($products as $p) {
                $product_num += $p->num;
                $product[] = [
                    'id' => $p->product_id,
                    'name' => $p->name,
                    'image' => $p->image,
                    'price' => number_format($p->price, 2),
                    'num' => $p->num,
                ];
            }
            $data = [
                'id' => $order->id,
                'order_sn' => $order->order_sn,
                'consignment_type' => $order->consignment_type,
                'status' => $order->status,
                'status_text' => get_order_status($order->status, $order->type),
                'comment_status' => $order->comment_status,
                'after_status' => $order->after_status,
                'consignee' => $order->consignee,
                'mobile' => $order->mobile,
                'address' => $order->address,
                'price' => number_format($order->price, 2),
                'create_time' => $order->create_time,
                'type' => $order->type,
                'msg' => $order->msg,
                'express_sn' => $order->express_sn,
                'shop_id' => $order->shop_id,
                'shop_logo' => $order->shop_id ? get_img_url($order->shop->logo) : '',
                'shop_name' => $order->shop_id ? $order->shop->name : '',
                'shop_level' => $order->shop_id ? ($order->shop->commentLevel() > 0 ? $order->shop->commentLevel() : 5) : 5,
                'products' => $product,
                'products_num' => $product_num
            ];

            return api_return(200, $data);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 取消订单
     * @param $param
     * @return array
     */
    public static function cancel_order($param) {
        try {
            $order = model('order')->get(['id' => $param['order_id'], 'member_id' => $param['member_id']]);
            if (!$order) {
                throw new \Exception('产品不存在');
            }

            if ($order->status > 3 ) {
                throw new \Exception('订单状态异常');
            }
            model('order')->save(['status' => 7], ['id' => $param['order_id'], 'member_id' => $param['member_id']]);
            return api_return(200, []);
        } catch (\Exception $e) {
            Db::rollback();
            return api_return(0, '', $e->getMessage());
        }
    }

    /**
     * 退回商家重新定价
     * @param $param
     * @return array
     */
    public static function back_merchant($param) {
        try {
            $order = model('order')->get(['id' => $param['order_id'], 'member_id' => $param['member_id']]);
            if (!$order) {
                throw new \Exception('产品不存在');
            }

            if ($order->status != 3 ) {
                throw new \Exception('订单状态异常');
            }
            model('order')->save(['status' => 2], ['id' => $param['order_id'], 'member_id' => $param['member_id']]);
            return api_return(200, []);
        } catch (\Exception $e) {
            Db::rollback();
            return api_return(0, '', $e->getMessage());
        }
    }

    /**
     * 确认收货
     * @param $param
     * @return array
     */
    public static function confirm_receipt($param) {
        try {
            $order = model('order')->get(['id' => $param['order_id'], 'member_id' => $param['member_id']]);
            if (!$order) {
                throw new \Exception('产品不存在');
            }

            if ($order->status != 4 ) {
                throw new \Exception('订单状态异常');
            }
            model('order')->save(['status' => 6, 'delivery_time' => time()], ['id' => $param['order_id'], 'member_id' => $param['member_id']]);
            return api_return(200, []);
        } catch (\Exception $e) {
            Db::rollback();
            return api_return(0, '', $e->getMessage());
        }
    }
}